package dao

import (
	"context"
	"database/sql"
	"gitee.com/itgsyang/restful-api-demo/apps/hosts"
	"go.uber.org/zap"
)

var _ hosts.HostEntityService = &HostDao{}

type HostDao struct {
	l  *zap.Logger
	db *sql.DB
}

func (h2 *HostDao) CreateHost(ctx context.Context, ins hosts.Host) (hosts.Host, error) {
	if err := ins.Validate(); err != nil {
		return hosts.Host{}, err
	}
	// 插入数据
	var err error
	tx, err := h2.db.BeginTx(ctx, nil)
	if err != nil {
		return hosts.Host{}, err
	}

	defer func() {
		if err != nil {
			if err = tx.Rollback(); err != nil {
				h2.l.Error("数据库回滚失败", zap.Error(err))
			}
		} else {
			if err = tx.Commit(); err != nil {
				h2.l.Error("数据库提交失败", zap.Error(err))
			}
		}
	}()
	rsmt, err := tx.Prepare(hosts.InsertResourceSQL)

	if err != nil {
		return hosts.Host{}, err
	}
	defer rsmt.Close()
	if rsmt != nil {
		_, err = rsmt.Exec(ins.Id, ins.Vendor, ins.Region, ins.CreateAt, ins.ExpireAt, ins.Type,
			ins.Name, ins.Description, ins.Status, ins.UpdateAt, ins.SyncAt, ins.Account, ins.PublicIP,
			ins.PrivateIP)
	}

	if err != nil {
		return hosts.Host{}, err
	}

	desmt, err := tx.Prepare(hosts.InsertDescribeSQL)
	defer func() {
		if desmt != nil {
			desmt.Close()
		}
	}()
	if err != nil {
		return hosts.Host{}, err
	}
	if desmt != nil {
		_, err = desmt.Exec(ins.Id, ins.CPU, ins.Memory, ins.GPUAmount, ins.GPUSpec,
			ins.OSType, ins.OSName, ins.SerialNumber)
	}

	if err != nil {
		return hosts.Host{}, err
	}

	return ins, nil
}

func (h2 *HostDao) QueryHost(ctx context.Context, req hosts.QuerHostReq) (hosts.HostSet, error) {
	//TODO implement me
	panic("implement me")
}

func (h2 *HostDao) UpdateHost(ctx context.Context, h hosts.Host) (hosts.Host, error) {
	//TODO implement me
	panic("implement me")
}

func (h2 *HostDao) DeleteHost(ctx context.Context, req hosts.DeleteHostReq) (hosts.Host, error) {
	//TODO implement me
	panic("implement me")
}

func NewHostDao(l *zap.Logger, db *sql.DB) hosts.HostEntityService {
	return &HostDao{
		l:  l,
		db: db,
	}
}
